const jwt = require('jsonwebtoken');
const { User } = require('../models');
const { Unauthorized } = require('http-errors');
const { success, failure } = require('../utils/responses');

module.exports = async (req, res, next) => {
  try {
    const token = req.headers.token || req.query.token;

    if (!token) {
      throw new Unauthorized('当前接口需要登录');
    }
    const decoded = jwt.verify(token, process.env.SECRET);
    //从token中解析出用户id
    const { userId } = decoded;
    const user = await User.findByPk(userId);
    if (!user) {
      throw new Unauthorized('用户不存在');
    }
    // 验证当前用户是否是管理员
    if (user.role !== 100) {
      throw new Unauthorized('您没有权限使用当前接口。');
    }
    // 如果通过验证，将 user 对象挂载到 req 上，方便后续中间件或路由使用
    req.user = user;
    req.userId = user.id;
    next();
  } catch (error) {
    failure({ res, error, message: '请先登录', code: 401 });
  }
};
